#include "admsql.h"
#include <QMessageBox>
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QSqlError>
#include <QDebug>
#include <QFile>
#include<QCoreApplication>
#include<QCryptographicHash>
#include<QDir>
#include <QApplication>
AdmSql::AdmSql(QObject *parent)
    : QObject(parent)
{
    init();
}
 // 打开数据库
void AdmSql::init()
{
    m_db = QSqlDatabase::addDatabase("QSQLITE");
    m_db.setDatabaseName("sqlite.db");
    if (!m_db.open()) {
        qDebug() << "无法打开数据库:" << m_db.lastError().text();
    }
}
QList<AdmInfo> AdmSql::getAllAdm()
{
    QSqlQuery sql;
    //输出查询结果
    QList<AdmInfo> list_a;
    AdmInfo a;
    if (!sql.exec("SELECT * FROM administrator")) {
        qWarning() << "Failed to execute query:" << sql.lastError().text();
    }
    else{
        while (sql.next()) {
            a.aid= sql.value(0).toString();
            a.aname = sql.value(1).toString();
            a.email = sql.value(2).toString();
            a.password="******";
            list_a.push_back(a);
        }
    }
    return list_a;
}

bool AdmSql::TheAdmIsExit(QString strAdm)
{
    QSqlQuery sql;
    sql.prepare("SELECT * FROM administrator WHERE aname = :aname");
    sql.bindValue(":aname", strAdm);
    if (!sql.exec()) {
        qWarning() << "Failed to execute query:" << sql.lastError().text();
        return false;
    }
    return sql.next();
}

bool AdmSql::EmailExit(QString email)
{
    QSqlQuery sql;
    sql.prepare("SELECT * FROM administrator WHERE email = :email");
    sql.bindValue(":email", email);
    if (!sql.exec()) {
        qWarning() << "Failed to execute query:" << sql.lastError().text();
        return false;
    }
    return sql.next();
}

bool AdmSql::IdIsExit(QString id)
{
    QSqlQuery sql;
    sql.prepare("SELECT * FROM administrator WHERE aid = :aid");
    sql.bindValue(":aname", id);
    if (!sql.exec()) {
        qWarning() << "Failed to execute query:" << sql.lastError().text();
        return false;
    }
    return sql.next();
}
bool AdmSql::LoginIsRight(QString strAdm, QString password, AdmInfo *adminInfo)
{
    QSqlQuery sql;
    // 对用户输入的密码进行哈希处理
    QString hashedPassword = QCryptographicHash::hash(password.toUtf8(), QCryptographicHash::Sha256).toHex();
    sql.prepare("SELECT * FROM administrator WHERE aname = :aname AND password = :password");
    sql.bindValue(":aname", strAdm);
    sql.bindValue(":password", hashedPassword);  // 绑定哈希值
    if (!sql.exec()) {
        qWarning() << "Failed to execute query:" << sql.lastError().text();
        return false;
    }
    if (sql.first()) {
        adminInfo->aid = sql.value(0).toString();
        adminInfo->aname = sql.value(1).toString();
        adminInfo->email = sql.value(2).toString();

        qDebug() << "Login successful for admin:" << adminInfo->aname;
        return true;
    } else {
        qDebug() << "No matching records found.";
        return false; // 如果没有找到匹配项，则登录失败
    }
}

bool AdmSql::AddAdm(AdmInfo info)
{
    QSqlQuery sql;
    QString strSql=QString("insert into administrator values('%0','%1','%2','%3')").
                     arg(info.aid).
                     arg(info.aname).
                     arg(info.email).
                     arg(info.password);
    return sql.exec(strSql);
}

bool AdmSql::updateAdminInfo(const AdmInfo &info)
{
    QSqlQuery query;
    // 更新数据库中的管理员信息
    query.prepare("UPDATE administrator SET aname = :aname, email = :email WHERE aid = :aid");
    query.bindValue(":aname", info.aname);
    query.bindValue(":email", info.email);
    query.bindValue(":aid", info.aid);

    if (!query.exec()) {
        qWarning() << "更新密码失败:" << query.lastError().text();
        return false;
    }

    qDebug() << "更新密码成功:" << info.aid;
    return true;
}

bool AdmSql::changePassword(const QString &aid, const QString &oldPassword, const QString &newPassword)
{
    QSqlQuery query;
    // 对用户输入的旧密码进行哈希处理
    QString hashedOldPassword = QString(QCryptographicHash::hash(oldPassword.toUtf8(), QCryptographicHash::Sha256).toHex());
    qDebug() << "Hashed old password:" << hashedOldPassword;
    // 查询数据库中的密码
    query.prepare("SELECT password FROM administrator WHERE aid = :aid");
    query.bindValue(":aid", aid);
    qDebug() << "Executing query:" << query.lastQuery();
    qDebug() << "Bound values:" << query.boundValues();
    if (!query.exec()) {
        qWarning() << "查询验证旧密码失败:" << query.lastError().text();
        return false;
    }
    if (query.next()) {
        QString dbPassword = query.value(0).toString();
        qDebug() << "Database password:" << dbPassword;
        // 比较哈希值
        if (dbPassword == hashedOldPassword) {
            qDebug() << "Old password matches.";
        } else {
            qDebug() << "Old password does not match.";
            return false;
        }
    } else {
        qDebug() << "No record found for aid:" << aid;
        return false;
    }
    // 如果旧密码匹配，更新新密码
    QString hashedNewPassword = QString(QCryptographicHash::hash(newPassword.toUtf8(), QCryptographicHash::Sha256).toHex());
    qDebug() << "Hashed new password:" << hashedNewPassword;

    query.prepare("UPDATE administrator SET password = :password WHERE aid = :aid");
    query.bindValue(":password", hashedNewPassword);
    query.bindValue(":aid", aid);

    qDebug() << "Executing update query:" << query.lastQuery();
    qDebug() << "Bound values:" << query.boundValues();

    if (!query.exec()) {
        qWarning() << "更新密码失败:" << query.lastError().text();
        return false;
    }

    qDebug() << "admin的密码修改成功：" << aid;
    return true;
}

bool AdmSql::resetPassword(QString email, QString newPassword)
{
    QSqlQuery query;
    QString hashedNewPassword = QString(QCryptographicHash::hash(newPassword.toUtf8(), QCryptographicHash::Sha256).toHex());
    // 更新数据库中的管理员信息
    query.prepare("UPDATE administrator SET password = :password WHERE email = :email");
    query.bindValue(":password", hashedNewPassword);
    query.bindValue(":email", email);
    if (!query.exec()) {
        qWarning() << "更新密码失败:" << query.lastError().text();
        return false;
    }
    qDebug() << "更新密码成功:";
    return true;
}
AdmInfo AdmSql::getAdminInfoByAid(const QString &aid)
{
    AdmInfo adminInfo;
    QSqlQuery query;
    query.prepare("SELECT aid, aname, email,password FROM administrator WHERE aid = :aid");
    query.bindValue(":aid", aid);
    if (query.exec() && query.next()) {
        adminInfo.aid = query.value(0).toString();
        adminInfo.aname = query.value(1).toString();
        adminInfo.email = query.value(2).toString();
        adminInfo.password=query.value(3).toString();
        qDebug() << "通过账户的查询结果:" << adminInfo.aid;
    } else {
        qWarning() << "通过账户查询失败:" << aid;
        qDebug() << "Query error:" << query.lastError().text();
    }

    return adminInfo;
}

